package com.tiancheng.trade.order.controller.app;

import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.order.util.SecurityUtils;
import com.tiancheng.trade.order.model.ReportChannel;
import com.tiancheng.trade.order.model.ReportRecord;
import com.tiancheng.trade.order.service.ReportChannelService;
import com.tiancheng.trade.order.util.cache.ReportCache;
import com.tiancheng.trade.order.vo.app.ChannelReportCacheVO;
import com.tiancheng.trade.order.vo.app.ChannelReportVO;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotEmpty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author: likailun
 * @Description: 上报控制器
 * @Date: create in 2022/12/20 11:28
 */
@RestController
@RequestMapping("/app/report")
@Validated
@Slf4j
public class ReportController {

    @Resource
    private ReportCache reportCache;
    @Resource
    private ReportChannelService reportChannelService;
    private static List<String> sources=new ArrayList<String>(){{add("魔方");add("线路");add("订单");add("旅行套餐");add("门票");}};
    /**
     * 缓存用户信息
     *
     * @param params
     * @return
     */
    @PostMapping(value = "/channel/cache",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result cache(@RequestBody ChannelReportCacheVO params, @RequestHeader HttpHeaders headers) {
        if(MapUtils.isEmpty(params.getArgs()) || StringUtils.isEmpty(params.getColumnName())||StringUtils.isEmpty(params.getColumnId())){
            return Result.fail("关键参数args、columnName、columnId为空");
        }
        String uid = SecurityUtils.getLoginUserId();
        log.info("广告参数缓存uid:{}",uid);
        if(params==null){
            if(null==params.getIsClearKey() || params.getIsClearKey()){
                reportCache.delUserReportArg(uid);
            }
            return Result.fail("参数为空");
        }
        if(!sources.contains(params.getColumnName())){
            if(null==params.getIsClearKey() || params.getIsClearKey()){
                reportCache.delUserReportArg(uid);
            }
            return Result.fail("未知的渠道");
        }
        List<ReportChannel> reportChannels=null;
        final Optional<List<ReportChannel>> channel = reportCache.getChannel();
        if(channel.isPresent()){
            reportChannels=channel.get();
        }else {
            reportChannels = reportChannelService.queryReportChannel(0, false);
            reportCache.cacheChannel(reportChannels);
        }

        if(CollectionUtils.isEmpty(reportChannels)){
            if(null==params.getIsClearKey() || params.getIsClearKey()){
                reportCache.delUserReportArg(uid);
            }
            return Result.fail("无渠道配置");
        }
        // 判断是否存在核心参数
        for (ReportChannel reportChannel : reportChannels) {
            if(params.getArgs().containsKey(reportChannel.getMainArg())){
                final String s = reportCache.cacheUserReportArg(uid, params);
                return Result.success(s);
            }
        }
        if(null==params.getIsClearKey() || params.getIsClearKey()){
            reportCache.delUserReportArg(uid);
        }
        return Result.fail("不满足上报条件");
    }


    @GetMapping(value = "/channel/getCache")
    public Result<ChannelReportCacheVO> getCache(@RequestParam("key") @NotEmpty String key) {
        final Optional<ChannelReportCacheVO> userReportArg = reportCache.getUserReportArg(key);
        return Result.success(userReportArg.get());
    }


    @PostMapping(value = "/channel/report",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<ChannelReportCacheVO> report( @RequestBody ChannelReportVO params, @RequestHeader HttpHeaders headers) {
        if(StringUtils.isEmpty(params.getUserKey()) || StringUtils.isEmpty(params.getPageStack())||StringUtils.isEmpty(params.getOrderId())){
            return Result.fail("关键参数userKey、pageStack、orderId为空",null);
        }
        String uid = SecurityUtils.getLoginUserId();
        if(null==params){
            return Result.fail("参数异常",null);
        }
        return reportChannelService.report(params,uid);
    }


    @GetMapping(value = "/channel/record")
    public Result<List<ReportRecord>> reportRecord(@RequestParam("order_id") @NotEmpty String orderId) {
        return Result.success(reportChannelService.queryReportRecord(orderId));
    }


    /**
     * 删除缓存的渠道信息
     * 测试用
     * @param headers
     * @return
     */
    @GetMapping(value = "/channel/clearChannel",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result clearChannel( @RequestHeader HttpHeaders headers) {
        String uid = SecurityUtils.getLoginUserId();
        reportCache.delChannel();
        return Result.success();
    }

    /**
     * 删除缓存的用户广告参数
     * 测试用
     * @param headers
     * @return
     */
    @GetMapping(value = "/channel/clearUserCache",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result clearCache( @RequestHeader HttpHeaders headers) {
        String uid = SecurityUtils.getLoginUserId();
        reportChannelService.clearCache(uid);
        return Result.success();
    }

    /**
     * 删除缓存的配置，在手动维护配置的时候可以用这个借口来作废之前缓存的配置
     * @param headers
     * @return
     */
    @PostMapping(value = "/channel/clearChannelCache",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result clearChannelCache(@RequestBody Map<String,Object> params, @RequestHeader HttpHeaders headers) {
        if(null!=params && StringUtils.isNotEmpty(MapUtils.getString(params,"main_arg"))){
            reportChannelService.clearChannelCache(MapUtils.getString(params,"main_arg"));
        }
        return Result.success();
    }

}
